<?php
/**
 * Created by PhpStorm.
 * User: wangsong
 * Time: 2018/7/25 11:26
 */

namespace App\Project\Search\Decorator;

use App\Project\Search\Decorator;
use App\Project\Search\Raw;
use Illuminate\Database\Eloquent\Relations\HasMany;

class CnDiagnoseDecorator extends Decorator
{
    protected $table = 'st_cn_diagnoses';

    protected $prefix = 'cn_diagnose';

    public function getBuilder()
    {
        return $this->fillBuilder([
            $this->table,
            'st_medical_records.id',
            $this->table . '.record_id'
        ]);
    }

    public function getAccessField()
    {
        return [
            'd' => ''
        ];
    }

    public function getAccessOperator()
    {
        return [
            'd' => ['all']
        ];
    }

    protected function findInSet($carryKey)
    {
        return Raw::findInSet($this->table . '.carry_key', $carryKey);
    }

    protected function condition($condition, $key)
    {
        static $ids = null;
        $sql = 'st_medical_records.id in ';

        if (is_null($ids)) {

            $fragment = [];

            foreach ($condition['value'] as $index => $item) {
                $fragment[$index] = " cn_disease_id = {$item['cn_disease_id']} and type_id = {$item['type_id']} ";
                if (isset($item['carry_key']))
                    foreach ($item['carry_key'] as $value) {
                        $fragment[$index] .= "and FIND_IN_SET('$value', $this->table.carry_key)";
                    }

                $fragment[$index] = '(' . $fragment[$index] . ')';
            }

            $diagnoses = \DB::table('st_cn_diagnoses')->select(['id', 'record_id'])
                            ->whereRaw(implode(' or ', $fragment))
                            ->get();

            $length = count($condition['value']);
            $ids    = $diagnoses->groupBy('record_id')->filter(function ($diagnose) use ($length) {
                return $diagnose->count() >= $length;
            })->flatten();
        }

        if ($this->canAddSelect($condition) && $ids->count()) {
            $this->db->with([
                'cnDiagnose' => function (HasMany $hasMany) use ($ids) {
                    $hasMany->whereIn($this->table . '.id', $ids->pluck('id'));
                }, 'cnDiagnose.disease'
            ]);
        }

        if ($ids->count()) {
            return [$sql . '(' . $ids->pluck('record_id')->unique()->implode(', ') . ')'];
        } else {
            return ['1=0'];
        }
    }
}